package com.example.baidu.speech.shorts.controller;

import com.example.api.common.utils.Result;
import com.example.baidu.speech.common.enums.BaiduSpeechFileSuffixEnum;
import com.example.baidu.speech.shorts.dto.BaiduSpeechShortDTO;
import com.example.baidu.speech.shorts.service.BaiduSpeechShortService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

/**
 * 百度短语音
 *
 * @author hspcadmin
 */
@Slf4j
@RestController
@RequestMapping(value = "/baidu/speech/short")
public class BaiduSpeechShortController {

    @Autowired
    private BaiduSpeechShortService BaiduSpeechShortService;

    @PostMapping("/recognizingShortSpeechByte")
    public Result<String> recognizingShortSpeechByte(@RequestParam("fileType") String fileType, @RequestBody byte[] bytes) {

        BaiduSpeechShortDTO baiduSpeechShortDTO =
                new BaiduSpeechShortDTO()
                        .setFormat(fileType)
                        .setBytes(bytes);

        String speechText = BaiduSpeechShortService.recognizingShortSpeechByte(baiduSpeechShortDTO);
        return Result.success(speechText);
    }

    @PostMapping("/recognizingShortSpeech")
    public Result<String> recognizingShortSpeech(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            throw new RuntimeException("文件名不能为空");
        }

        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        boolean supported = BaiduSpeechFileSuffixEnum.isSupported(fileSuffix);
        if (!supported) {
            throw new RuntimeException("不支持当前文件格式[" + fileSuffix + "]");
        }
        log.info("识别的短语音文件名：[{}]", originalFilename);

        BaiduSpeechShortDTO baiduSpeechShortDTO =
                new BaiduSpeechShortDTO()
                        .setFormat(fileSuffix)
                        .setSpeech(encodeToString(file))
                        .setLen(getSpeechByteLength(file));

        String speechText = BaiduSpeechShortService.recognizingShortSpeech(baiduSpeechShortDTO);
        return Result.success(speechText);
    }

    /**
     * base64编码
     *
     * @param file MultipartFile文件对象
     * @return base64编码后的结果
     */
    private String encodeToString(MultipartFile file) {
        try {
            return Base64.getEncoder().encodeToString(file.getBytes());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("Base64编码失败");
        }
    }

    /**
     * 获取文件字节长度
     *
     * @param file MultipartFile文件对象
     * @return 文件字节长度
     */
    private int getSpeechByteLength(MultipartFile file) {
        try {
            return file.getBytes().length;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("获取文件大小失败");
        }
    }

}
